package com.example.jobseek;

import java.util.Vector;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.example.jobseek.Login.log;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import domain.PersonaVO;
import domain.TrabajoVO;
import android.support.v7.app.ActionBarActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DetalleEmpleo extends ActionBarActivity {

	
	TextView area;
	TextView titulo;
	TextView descripcion;
	TextView empresa;
	Button postular;
	String datos;
	String tipo;
	String datosLog;
	String rut;
	String postulado;
	JsonObject jobj;
	Bundle bundle;
	JSONArray aJson;
	JSONObject trabajson;
	JSONObject empresaJson;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detalle_empleo);
		bundle = this.getIntent().getExtras();
		datos = bundle.getString("datos");
		tipo = bundle.getString("tipo");
		if (tipo.equals("user")){
			datosLog = bundle.getString("rut");
			
			jobj = new Gson().fromJson(datosLog, JsonObject.class); 
			rut = jobj.get("run").toString().replace("\"", "");
			
		}
		titulo = (TextView)findViewById(R.id.titulo);
		area = (TextView)findViewById(R.id.area); 
		descripcion = (TextView)findViewById(R.id.descripcion);
		empresa = (TextView)findViewById(R.id.empresa);
		postular = (Button)findViewById(R.id.postular);
		
		try {
			
			
			aJson = new JSONArray(datos);
			trabajson = aJson.getJSONObject(0);
			empresaJson = new JSONObject(trabajson.getString("empresaid_empresa"));
			
			titulo.setText(trabajson.getString("nombre"));
			area.setText(trabajson.getString("area"));
			empresa.setText(empresaJson.getString("nombre"));
			descripcion.setText(trabajson.getString("descripcion"));
			
			if (tipo != "guest"){
				postulado = new postulado().execute(rut, trabajson.getString("nombre")).get();
				
				if (postulado.equals("postulado")){
					postular.setVisibility(View.GONE);
				}
			}
			if (tipo.equals("guest")){
				
				postular.setVisibility(View.GONE);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
		
		
		postular.setOnClickListener(new OnClickListener() {
	        
			@Override
			public void onClick(View arg0) {
				 
				try {
					
					new action().execute(rut ,trabajson.getString("nombre"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.detalle_empleo, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	class action extends AsyncTask<String, Void, String> {
		private static final String TAG = "postular";
		ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(DetalleEmpleo.this, "Cargando...",
					"Espere", true, true);

		}

		@Override
		protected String doInBackground(String... params) {
			String run = params[0];
			String name = params[1];

			String result = "";

			try {
				
				PersonaVO personaVO = new PersonaVO(run);
				TrabajoVO trabajoVO = new TrabajoVO(name);
				result = postular(personaVO, trabajoVO);
				Log.i(TAG, result);

			} catch (Exception e) {
				Log.e(TAG, e.getCause().toString());
			}

			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();

			if ("".equals(result)) {
				Toast.makeText(DetalleEmpleo.this,
						"Existe problemas de conectividad con el servidor",
						Toast.LENGTH_SHORT).show();
			} else if (result.contains("Error")) {
				Toast.makeText(getApplicationContext(), result,
						Toast.LENGTH_LONG).show();
			} else {
				Bundle b = new Bundle();
				b.putString("datosLog", datosLog);
				Intent i = new Intent(DetalleEmpleo.this, ListaEmpleos.class);
				i.putExtras(b);
				startActivity(i);

			}

		}
	}
	
	class postulado extends AsyncTask<String, Void, String> {
		

		@Override
		protected String doInBackground(String... params) {
			String run = params[0];
			String name = params[1];

			String result = "";

			try {
				
				PersonaVO personaVO = new PersonaVO(run);
				TrabajoVO trabajoVO = new TrabajoVO(name);
				result = estaPostulado(personaVO, trabajoVO);
				

			} catch (Exception e) {
				Log.e("error", e.getMessage());
			}

			return result;
		}

	}
	
	public String postular(PersonaVO oPersonaVO, TrabajoVO oTrabajoVO) {
        
        String method = "postular";
        String TAG = method;
        Log.i("intentando enviar datos al ws usando: ", method);

              try{  
                String SOAP_ACTION = util.Constantes.NAMESPACE+"#"+method;
                System.out.println(SOAP_ACTION);
                SoapObject request = new SoapObject(util.Constantes.NAMESPACE, method);

                
                request.addProperty("rut", oPersonaVO.getRut());
                request.addProperty("nombre", oTrabajoVO.getNombre());
                
             
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
                envelope.setOutputSoapObject(request);
                
                //envelope.addMapping(util.Constantes.NAMESPACE, "PersonaVO", new PersonaVO().getClass());

                HttpTransportSE transporte = new HttpTransportSE(util.Constantes.URL);
                transporte.debug = true;

                transporte.call(SOAP_ACTION, envelope);
              
                Log.i(TAG, "dump Request: "+ transporte.requestDump);
                        Log.i(TAG, "dump Response: "+ transporte.responseDump);
                        
                Vector response =(Vector)envelope.getResponse();
                String res = (String)response.get(1);
                        
                        return res;
                        
                }catch (Exception e) 
                {
                       e.printStackTrace();
                       
                }  
 
  return null;
  }
	
public String estaPostulado(PersonaVO oPersonaVO, TrabajoVO oTrabajoVO) {
        
        String method = "estaPostulado";
        String TAG = method;
        Log.i("intentando enviar datos al ws usando: ", method);

              try{  
                String SOAP_ACTION = util.Constantes.NAMESPACE+"#"+method;
                System.out.println(SOAP_ACTION);
                SoapObject request = new SoapObject(util.Constantes.NAMESPACE, method);

                
                request.addProperty("rut", oPersonaVO.getRut());
                request.addProperty("nombre", oTrabajoVO.getNombre());
                
             
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
                envelope.setOutputSoapObject(request);
                
                //envelope.addMapping(util.Constantes.NAMESPACE, "PersonaVO", new PersonaVO().getClass());

                HttpTransportSE transporte = new HttpTransportSE(util.Constantes.URL);
                transporte.debug = true;

                transporte.call(SOAP_ACTION, envelope);
              
                Log.i(TAG, "dump Request: "+ transporte.requestDump);
                        Log.i(TAG, "dump Response: "+ transporte.responseDump);
                        
                Vector response =(Vector)envelope.getResponse();
                String res = (String)response.get(1);
                        
                        return res;
                        
                }catch (Exception e) 
                {
                       e.printStackTrace();
                       
                }  
 
  return null;
  }
}
